/**
 * 
 */
package com.rw.daoImpl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.rw.dao.FavoritemDao;
import com.rw.table.Favoritem;

/**
 *
 *
 */
public class FavoritemDaoImpl extends HibernateDaoSupport implements FavoritemDao {
	
	public Favoritem get(Long userId) {

		return this.getHibernateTemplate().get(Favoritem.class, userId);
	}
	@Override
	public boolean add(Favoritem favoritem) {

		if((Long)this.getHibernateTemplate().save(favoritem) < 0) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public boolean delete(Long favoriteItemId) {

		try {
			this.getHibernateTemplate().delete(this.get(favoriteItemId));
		} catch (Exception e) {

			return false;
		}
		
		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Favoritem> get(final Long favoriteUserId, final int nowPage, final int pageSize) {

		List<Favoritem> favoritems = this.getHibernateTemplate().executeFind(new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException,
					SQLException {

				Query query = session.createQuery("select t from Favoritem t where t.favoriteUserId = " + "'" + favoriteUserId +"'");
				query.setFirstResult((nowPage - 1) * pageSize);
				query.setMaxResults(pageSize);
				Object object = query.list();
				session.close();
				return object;
			}
		});
		
		return favoritems;
	}

	@Override
	public boolean update(Favoritem favorite) {

		try {
			this.getHibernateTemplate().update(favorite);
		} catch (Exception e) {

			return false ;
		}
		
		return true;
	}
	
	@Override
	public List<Favoritem> findFavByUserId(Long userId){
		
		@SuppressWarnings("unchecked")
		List<Favoritem> Favoritems = (List<Favoritem>) this.getHibernateTemplate().find("select t from Favoritem t where t.favoriteUserId = ?", userId);
		
		return Favoritems;
	}
		
}
